package com.think.service;

import com.think.dao.mapper.UserDaoMapper;
import com.think.model.Role;
import com.think.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;

/**
 * Created by Administrator on 2018/5/25 0025.
 */
@Service
public class CustomUserService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(CustomUserService.class);

    @Autowired
    private UserDaoMapper userDaoMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDaoMapper.findByUserName(username);
        if(user == null){
            throw new UsernameNotFoundException("用户名："+ username + "不存在！");
        }


        Collection<SimpleGrantedAuthority> collection = new HashSet<SimpleGrantedAuthority>();
        //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
        for(Role role:user.getRoles()) {
            collection.add(new SimpleGrantedAuthority(role.getName()));
        }
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),collection);

        //同样可行
//        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
//        for(Role role:user.getRoles()) {
//            authorities.add(new SimpleGrantedAuthority(role.getName()));
//        }
//        user.setGrantedAuthorities(authorities);
//        return user;
    }
}
